﻿/**************************************************************************
创建时间:	2020/5/14 15:08:36    
作	  者:	张存
邮 	  箱:	zhangcunliang@126.com

Copyright (c) 河北朝仁医药科技有限公司

描	述：
记	录：
***************************************************************************/
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ZhCun.DbCore.BuildSQLText;
using ZhCun.DBModel;
using ZhCun.Utils;
using ZhCun.Utils.Helpers;

namespace ZhCun.Win.ExtendSearch
{
    public partial class FrmADSearch : FrmBaseModal
    {
        public FrmADSearch()
        {
            InitializeComponent();
        }

        public FrmADSearch(ISqlBuilder sql, string dgvName = "dgv")
        {
            InitializeComponent();
            _DgvName = dgvName;
            _Sql = sql;
            _Sql.ClearResult();
        }

        ISqlBuilder _Sql;
        string _DgvName;
        string _FormName;
        Sys_ADRecord _CurrRecord;
        List<Sys_GridColumn> _ColumnList;
        SearchBLL _BLL;
        
        void ClearSearchDetail()
        {
            flowLayoutPanel1.Controls.Clear();
        }
        /// <summary>
        /// 载入搜索记录
        /// </summary>
        void LoadSearchDetail()
        {
            ClearSearchDetail();
            var SearchDetail = _BLL.GetRecordDetail(_CurrRecord.Id);
            if (SearchDetail == null) return;
            for (int i = 0; i < SearchDetail.Count; i++)
            {
                U_ASRow u1 = new U_ASRow();
                if (i == 0)
                {
                    u1.IsFirstRow = true;
                }
                u1.InitiColumns(_ColumnList);
                u1.SetDetail(SearchDetail[i]);
                flowLayoutPanel1.Controls.Add(u1);
            }
        }
        /// <summary>
        /// 获取搜索明细结果
        /// </summary>
        List<Sys_ADRecord_Detail> GetSearchList()
        {
            List<Sys_ADRecord_Detail> list = new List<Sys_ADRecord_Detail>();
            int orderNo = 0;
            foreach (U_ASRow item in flowLayoutPanel1.Controls)
            {
                if (item == null) continue;
                Sys_ADRecord_Detail sm = new Sys_ADRecord_Detail();
                sm = item.GetDetail();
                if (sm == null) continue;
                sm.OrderNo = orderNo++;
                list.Add(sm);
            }
            return list;
        }
        /// <summary>
        /// 类型字符串转对象
        /// </summary>
        Type GetTypeByString(string typeStr)
        {
            EnumHelper.StringToEnum(typeStr, out AdDataType dataType);
            switch (dataType)
            {

                case AdDataType.@int:
                    return typeof(int);
                case AdDataType.@decimal:
                    return typeof(decimal);
                case AdDataType.@bool:
                    return typeof(bool);
                case AdDataType.@datetime:
                    return typeof(DateTime);
                case AdDataType.@string:
                default:
                    return typeof(string);
            }
        }
        /// <summary>
        /// 生成sql
        /// </summary>
        void BuildSql(List<Sys_ADRecord_Detail> detailList)
        {
            foreach (var item in detailList)
            {               
                _Sql.AddSQLText($" {item.ConnectorSignStr}");
                _Sql.AddSQLText($" {item.FieldName}");
                _Sql.AddSQLText($" {item.CompareSignStr}");
                if (item.CompareSignStr.Contains("Like"))
                {
                    string likeStr = item.SearchValue;
                    if (!likeStr.Contains("%"))
                    {
                        likeStr = $"%{likeStr}%";
                    }
                    _Sql.AddSQLText($" {_Sql.AddParam(likeStr)}");
                }
                else
                {
                    var dataType = GetTypeByString(item.DataTypeStr);
                    object val = Convert.ChangeType(item.SearchValue, dataType);
                    _Sql.AddSQLText($" {_Sql.AddParam(val)}");
                }
            }
        }

        /// <summary>
        /// 模态打开高级搜索输入
        /// </summary>
        public bool ShowSearch(IFormContainer form)
        {
            _BLL = new SearchBLL(CurrentUserId);
            _FormName = form.ContainerName;
            _ColumnList = _BLL.GetColumns(_FormName, _DgvName);
            _CurrRecord = _BLL.GetDefRecord(_FormName, _DgvName);
            if (_CurrRecord == null)
            {
                _CurrRecord = new Sys_ADRecord();
                _CurrRecord.FormName = _FormName;
                _CurrRecord.DgvName = _DgvName;
                _CurrRecord.Caption = "缺省";
                _CurrRecord.CaptionCode = "qs";
            }
            else
            {
                LoadSearchDetail();
            }
            var ret = ShowDialog();
            return ret == DialogResult.OK;
        }

        private void FrmADSearch_Load(object sender, EventArgs e)
        { }

        private void tsBtnAddOneRow_Click(object sender, EventArgs e)
        {
            U_ASRow ua = new U_ASRow();
            ua.InitiColumns(_ColumnList);
            if (flowLayoutPanel1.Controls.Count == 0)
            {
                ua.IsFirstRow = true;
            }
            flowLayoutPanel1.Controls.Add(ua);
        }

        private void tsBtnClear_Click(object sender, EventArgs e)
        {
            ClearSearchDetail();
        }

        private void tsbtnSave_Click(object sender, EventArgs e)
        {
            var detailList = GetSearchList();
            if (detailList == null || detailList.Count == 0)
            {
                ShowMessage("搜索明细为空");
                return;
            }
            FrmADSave frm = new FrmADSave();

            var saveModel = new Sys_ADRecord
            {
                DgvName = this._DgvName,
                FormName = this._FormName
            };
            var arg = new EditFormArgs
            {
                SaveHandle = (m) => _BLL.SaveRecord(m as Sys_ADRecord, detailList),
                SaveModel = saveModel
            };
            var ret = frm.ShowDialog(arg);
            if (ret)
            {
                ShowMessage(ret.msg);
            }
        }

        private void tsBtnConfigLoad_Click(object sender, EventArgs e)
        {
            FrmADRecord frm = new FrmADRecord();
            frm.GetDataSource = (serVal) => _BLL.GetRecordList(_FormName, serVal, _DgvName);
            frm.SaveRecord = _BLL.UpdateRecord;
            frm.DelRecord = _BLL.DelRecord;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                _CurrRecord = frm.SelectedRecord;
                LoadSearchDetail();
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            var detailList = GetSearchList();
            _BLL.SaveRecord(_CurrRecord, detailList);
            BuildSql(detailList);
            this.DialogResult = DialogResult.OK;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
    }

    /// <summary>
    /// 高级搜索用到的数据类型
    /// </summary>
    public enum AdDataType
    {
        @string,
        @int,
        @decimal,
        @bool,
        @datetime
    }
}
